package com.hpin.fansea.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.BannerAdapter;
import com.hpin.fansea.adapter.CircleClassifyAdapter;
import com.hpin.fansea.base.BaseFragment;
import com.hpin.fansea.bean.BannerResult;
import com.hpin.fansea.bean.CircleClaBean;
import com.hpin.fansea.sale.GoodsActivity;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.lidroid.xutils.http.RequestParams;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 商圈fragment
 * Created by Administrator on 2015/7/15.
 */
public class CircleFragment extends BaseFragment {

    private List<BannerResult.BannerDetail> bannerLists = new ArrayList<BannerResult.BannerDetail>();
    private BannerAdapter mAdapter;
    private ViewPager vp_circlepage;
    //    private RecyclerView rcy_circle;
    private List<CircleClaBean.CircleResult> circleResults = new ArrayList<>();
    private GridView gv_classify;
    private CircleClassifyAdapter classifyAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_circle, null);

        initWidget(view);

        // 加载轮播图
        getBunnerFromNet();

        getCircleData();

        return view;
    }

    /**
     * 获取商圈分类数据
     */
    private void getCircleData() {

        HttpUtil.getInstance().setGetRequest("获取中...", getActivity(), Constant.WEB_ROOT + Constant.CIRCLECLASSIFYDATA
                + "?token=" + sp.getString(Constant.token, "") + "&systemType=" + Constant.SYSTEM_TYPE, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    CircleClaBean circleClaBean = JSONObject.parseObject(str, CircleClaBean.class);

                    if (Constant.STATUS_SUCESS.equals(circleClaBean.status)) {

                        circleResults = circleClaBean.result;

//                        gv_classify.set
                        classifyAdapter.setCircleResults(circleResults);
                        classifyAdapter.notifyDataSetChanged();

                    } else {
                        showToast(circleClaBean.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(Constant.NODATA);
                }

            }
        }, null);

    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart(getClass().getName()); //统计页面

    }

    private void initWidget(View view) {

        vp_circlepage = (ViewPager) view.findViewById(R.id.vp_circlepage);

        gv_classify = (GridView) view.findViewById(R.id.gv_classify);

        classifyAdapter = new CircleClassifyAdapter(getActivity(), circleResults);

        gv_classify.setAdapter(classifyAdapter);

        gv_classify.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                if ("娱乐".equals(circleResults.get(position).catNm)
//                        || "美食".equals(circleResults.get(position).catNm)) {
//
//                    Intent mIntent = new Intent(getActivity(), WaitCircleActivity.class);
//                    startActivity(mIntent);
//
////                   showToast("暂未开放");
////                    return;
//                } else {

                    Intent mIntent = new Intent(getActivity(), GoodsActivity.class);
                    mIntent.putExtra("categoryId", circleResults.get(position).id_);
                    mIntent.putExtra("categoryName", circleResults.get(position).catNm);
                    startActivity(mIntent);
//
//                }

            }
        });

//        rcy_circle = (RecyclerView) view.findViewById(R.id.rcy_circle);
//
//        rcy_circle.setHasFixedSize(false);//RecyclerView不保持固定的大小
//        StaggeredGridLayoutManager sManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);//表示两列，并且是竖直方向的瀑布流
//        rcy_circle.setLayoutManager(sManager);
//
//        CircleWatefullAdaper wAdaper = new CircleWatefullAdaper();
//        rcy_circle.setAdapter(wAdaper);

    }

    /**
     * 获取轮播图
     */
    private void getBunnerFromNet() {

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("systemType", Constant.SYSTEM_TYPE);
        params.addQueryStringParameter("location", Constant.PURCHASEPAGER);
        params.addQueryStringParameter("projectId", sp.getString(Constant.communityId, ""));

        HttpUtil.getInstance().setGetRequest("加载中...", getActivity(), Constant.WEB_ROOT + Constant.GETBUNNER, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    BannerResult bannerResult = JSONObject.parseObject(str, BannerResult.class);

                    if (Constant.STATUS_SUCESS.equals(bannerResult.status)) {

                        bannerLists = bannerResult.result;

                        mAdapter = new BannerAdapter(bannerLists, getActivity());
                        vp_circlepage.setAdapter(mAdapter);

                        //开始轮播
                        startPlay();

                    } else {
                        showToast(bannerResult.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }

    private boolean actionNotDown = true;
    private static final int CHANGEPIC = 006;

    /**
     * 开始轮播
     */
    private void startPlay() {

        //设置无限轮播的起点
        if (bannerLists == null || bannerLists.size() == 0)
            return;

        int middle = Constant.MAX_SIZE / 2;

        int firstItem = (middle / bannerLists.size()) * bannerLists.size();

        LogUtil.e("tag", "firstItem===" + firstItem);

        vp_circlepage.setCurrentItem((middle / bannerLists.size()) * bannerLists.size());

        vp_circlepage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            /**
             * 当页面选择发生改变的时候，
             * position 新页面的下标
             */
            public void onPageSelected(int position) {

            }

            @Override
            /**
             * 当页面滑动时的回调监听
             */
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

//                 LogUtil.e("tag", "onPageScrolled===" + position);

                currentPosition = position;
            }

            @Override
            /**
             * 当页面的滑动状态发生改变的时候，
             * 如：手指按下状诚，滑动状态，抬起状态
             */
            public void onPageScrollStateChanged(int state) {
            }
        });

        vp_circlepage.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                actionNotDown = false;
                return false;
            }
        });

        // 让轮播图滚动
        if (isStop) {
            startRoll();
            isStop = false;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

//        LogUtil.e("TAG", "homepagefragment=====onDestroyView");

        isStop = false;
    }

    /**
     * 让轮播图滚动
     */
    public void startRoll() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                SystemClock.sleep(Constant.MSG_DELAY);
                handler.sendEmptyMessage(CHANGEPIC);
            }
        }).start();

    }

    private int currentPosition;
    private int item;
    private boolean isStop = true;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case CHANGEPIC:

                    if (actionNotDown) {

                        //做判断 以防万一
                        if (bannerLists == null || bannerLists.size() == 0 || bannerLists.size() == 1)
                            return;

                        item = (currentPosition++) % (bannerLists.size());
                        vp_circlepage.setCurrentItem(item, false);
                    } else {
                        actionNotDown = true;
                    }
                    startRoll();
                    break;
                default:
                    break;
            }

        }
    };

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getName());
    }


}
